package wechat

import (
	"errors"
	"fmt"
	"git.oschina.net/xuebing1110/amap"
	"github.com/chanxuehong/wechat/mp/message/request"
	"github.com/chanxuehong/wechat/mp/message/response"
	"net/url"
)

const (
	FMT_REG_NAME_FAIL = `尊敬的%s，注册姓名失败，失败编码：%s，请联系公众号管理员！`
	FMT_REG_NAME_SUC  = `尊敬的%s，注册姓名成功！`

	FMT_REG_TRANSCARD_FAIL = `尊敬的会员，绑定公交卡失败，失败编码：%s，请联系公众号管理员！`
	FMT_REG_TRANSCARD_SUC  = `尊敬的会员，绑定公交卡成功！`

	FMT_REG_HEADPIC_TEXT_SUC = `请上传头像照片！`

	FMT_REG_HEADPIC_FAIL = `上传图片失败，失败编码：%s，请联系公众号管理员！`
	FMT_REG_HEADPIC_SUC  = `上传图片成功！`

	DEVIMG_URL = "http://123.56.66.219:30003/wechat/wechatForm.jsp"

	//AMAP_KEY     = "b3abf03fa1e83992727f0625a918fe73"
	AMAP_TABLEID = "567500e0305a2a626c57d086"
)

func (user *User) UploadHeadPic() (string, error) {
	rownum, err := Orm.Id(user.UserID).Cols("headurl", "lastmsgtype").Update(user)
	if err != nil {
		return fmt.Sprintf(FMT_REG_HEADPIC_FAIL, `UPDATE_HEADURL_ERR`), err
	}

	if rownum != 1 {
		rownum, err = Orm.InsertOne(user)
		if err != nil || rownum != 1 {
			return fmt.Sprintf(FMT_REG_HEADPIC_FAIL, `INSERT_USER_HEADURL_ERR`), err
		}
	}

	return FMT_REG_HEADPIC_SUC, nil
}

func (user *User) UploadDevicePic(image *request.Image) *response.News {
	forword_url := fmt.Sprintf("%s?imgurl=%s&userid=%s&createtime=%d",
		DEVIMG_URL, url.QueryEscape(image.PicURL), user.UserID, image.CreateTime)

	resp := response.NewNews(
		image.FromUserName,
		image.ToUserName,
		image.CreateTime,
		[]response.Article{
			response.Article{
				Title:       "设备图片",
				Description: "请点击并输入设备信息!",
				PicURL:      image.PicURL,
				URL:         forword_url}})

	return resp
}

func (user *User) RegName() (string, error) {
	user.LastMsgType = MSGTYPE_REG_NAME
	rownum, err := Orm.Id(user.UserID).Cols("name", "lastmsgtype").Update(user)
	if err != nil {
		return fmt.Sprintf(FMT_REG_NAME_FAIL, user.Name, `UPDATE_NAME_ERR`), err
	}

	if rownum != 1 {
		rownum, err = Orm.InsertOne(user)
		if err != nil || rownum != 1 {
			return fmt.Sprintf(FMT_REG_NAME_FAIL, user.Name, `INSERT_USER_ERR`), err
		}
	}

	return fmt.Sprintf(FMT_REG_NAME_SUC, user.Name), nil
}

func (user *User) BindTransCard() (string, error) {
	rownum, err := Orm.Id(user.UserID).Cols("transcard").Update(user)
	if err != nil {
		return fmt.Sprintf(FMT_REG_TRANSCARD_FAIL, `UPDATE_TRANSCARD_ERR`), err
	}

	if rownum != 1 {
		rownum, err = Orm.InsertOne(user)
		if err != nil || rownum != 1 {
			return fmt.Sprintf(FMT_REG_TRANSCARD_FAIL, `INSERT_TRANSCARD_ERR`), err
		}
	}

	return FMT_REG_TRANSCARD_SUC, nil
}

func (user *User) QueryTransCard() (string, error) {
	querybool, err := Orm.Id(user.UserID).Get(user)
	if !querybool || err != nil {
		return "获取公交卡信息失败！", err
	} else if user.TransCard == "" {
		return "请先绑定公交卡信息，比如发送:琴岛通@xxxxxxxxx", nil
	} else {
		ret_v, ret_err := APIQuery.Query(user.UserID, user.TransCard)
		ret_str, _ := ret_v.(string)
		return ret_str, ret_err
	}
}

func (user *User) PrepareUploadHeadPic() (string, error) {
	rownum, err := Orm.Id(user.UserID).Cols("lastmsgtype").Update(user)
	if err != nil {
		return `UPDATE_LASTMSGTYPE_ERR`, err
	}

	if rownum != 1 {
		user := &User{
			UserID:      user.UserID,
			Name:        user.UserID,
			LastMsgType: MSGTYPE_REG_HEADPIC_TEXT}
		rownum, err = Orm.InsertOne(user)
		if err != nil || rownum != 1 {
			return `INSERT_LASTMSGTYPE_ERR`, err
		}
	}

	return FMT_REG_HEADPIC_TEXT_SUC, nil
}

func (user *User) UploadLocation() (string, error) {
	amap_key := APIQuery.Get("AMAP")
	if amap_key == "" {
		return "获取位置失败！", errors.New("the APIQuery \"AMAP\" is null or not set!")
	}

	//调用高德地图
	gdgeo, err := amap.GetAddrByLocation(user.Location, amap_key)
	if err != nil {
		return "获取位置失败！", err
	}

	//入位置历史表
	go func() {
		local_his := &UserHisLocations{
			UserID:     user.UserID,
			Location:   user.Location,
			Address:    user.Address,
			DetailAddr: user.DetailAddr,
			Aoi:        user.Aoi}
		Orm.InsertOne(local_his)
	}()

	//赋值高德调用结果
	user.DetailAddr = gdgeo.GetDetailLocation()
	user.Aoi = gdgeo.GetFirstLocationAoi()

	//更新高德云图
	ul := amap.UserLocation{
		amap_key,
		AMAP_TABLEID,
		user}
	_id, err_tmp := ul.UploadLocation(user.AmapID)
	if err_tmp != nil {
		return "定位成功，上传失败！", err_tmp
	}
	user.AmapID = _id

	//更新数据库
	rows, err_db := Orm.Id(user.UserID).Cols("headurl", "location", "address", "detailaddress", "aoi", "amapid").Update(user)
	if err_db != nil {
		return "定位成功，保存失败！", err_db
	} else if rows == 0 {
		return "定位成功，保存失败！", nil
	} else {
		return "定位成功，保存成功！", nil
	}
}
